<?php
	class Geocode extends AppModel
	{
		public $name = "Geocode";
		/**
		 * 
		 * @param array $location - keys address , city , country should be set. 
		 */
		function getCordinates(array $location)
		{
			$keys = array('address','city','state','country','postal_code');
			$locationArray = array();
			foreach($keys as $key)
			{
				$val = '';
				if(isset($location[$key]))
				{
					$val = trim($location[$key]);
				}
				if(strlen($val) > 0)
				{
					$locationArray[$key] = $val;
				}
			}
			$locationString = implode(", ",$locationArray);
			$result = $this->find("first",array('conditions'=>array("location like"=>$locationString)));
			$latLng = array();
			if($result)
			{
					$latLng = array("lat" => @$result[$this->alias]['lat'],'lng'=>@$result[$this->alias]['lng']);
			}else
			{
				$latLng =   $this->getLatLn($locationArray);
				$this->create();
				$data = $latLng;
				$data['location'] = $locationString;
				$this->save(array($this->alias => $data));
			}
			return $latLng;
		}

		
		/**
		 * get lat lang from google
		 */
		protected function getLatLn(array $location)
		{
			App::import("Vendor","Geo.GeoCoder");
			$services = array("Google",);
			$latLng = array();
			$geocode = false;
			foreach($services as $service)
			{
				$serviceClassName = $service.'GeoCoder';
				$params = array();
				if($service == "Google")
				{
					$params['region'] = cr('Geo.region');
				}
				$GeoCoderObject = new $serviceClassName;
				try
				{
					$geocode = $GeoCoderObject->getGeoCode($location,$params);			
				}catch(GeoCodeException $e)
				{
					
				}
				if(is_array($geocode))
				{
					break;
				}
			}
			return $geocode;
	
		}
	}
?>